package models

import (
	"database/sql"
	"log"
	"strconv"
	"time"

	"math/rand"
	"net/url"

	"strings"

	_ "github.com/go-sql-driver/mysql"
)

func init() {
	//init
}

type Stu_Lb struct {
	Id   int
	LbMc string
	Hide int
}

type Stu_Myddc struct {
	Lbs        []Stu_Lb   `json:"lb"`
	FormValues url.Values //提交的表单数据，切片类型
	Ip         string     //提交的IP地址
	Sj         string     //提交的时间
	Gh         string     //提交人的工号
	Xm         string     //提交人的姓名
	Dd         string     //提交地点
}

func (this *Stu_Myddc) GetDcLb() error {
	//从数据库中读取要读取 的调查列表
	var (
		sqlstr string
		rows   *sql.Rows
		err    error
		lb     Stu_Lb
	)
	sqlstr = `SELECT
			t1_sys.sys_id,
			t1_sys.sys_name,t1_sys.hide
			FROM
			t1_sys
			where parentId = 16 and deleted = 0`
	rows, err = db.Query(sqlstr)
	if err != nil {
		return err
	}
	for rows.Next() {
		err = rows.Scan(&lb.Id, &lb.LbMc, &lb.Hide)
		if err != nil {
			return err
		}
		this.Lbs = append(this.Lbs, lb)
	}
	return err
}

func (this *Stu_Myddc) SaveDcb() error { //调查数据存入数据库
	var (
		err         error
		tx          *sql.Tx
		sqlstr      string
		xm_id       int
		myddc_id    string //随机数，每个调查表的UUID
		myddc_type  int
		myddc_value string
	)
	xm_id = 1
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	myddc_id = strconv.FormatInt(r.Int63(), 10)
	log.Println("满意度调查的UUID，随机数：", r.Int63(), "，字符串：", myddc_id)
	sqlstr = "insert into myddc(xm_id,myddc_id,myddc_type,myddc_value) values(?,?,?,?)"
	tx, err = db.Begin()
	if err != nil {
		log.Println("插入满意度调查表时，初始化事务出错！", err)
		return err
	}
	for k, v := range this.FormValues {
		myddc_type, err = strconv.Atoi(k)
		if err != nil {
			log.Println("转换满意度调查类型为数值时出错！", err)
			return err
		}
		if myddc_type == 71 { //工号
			myddc_value = this.Gh
		} else if myddc_type == 72 { //ip
			myddc_value = this.Ip
		} else if myddc_type == 73 { //姓名
			myddc_value = this.Xm
		} else if myddc_type == 74 { //地点
			myddc_value = this.Dd
		} else if myddc_type == 75 { //时间
			myddc_value = this.Sj
		} else {
			myddc_value = strings.Join(v, "")
		}
		tx.Exec(sqlstr, xm_id, myddc_id, myddc_type, myddc_value)
		log.Println("插入表数据，myddc_type:", myddc_type, "\t myddc_value:", myddc_value)
	}
	/*
		tx.Exec(sqlstr, xm_id, myddc_id, "ip", this.Ip)
		tx.Exec(sqlstr, xm_id, myddc_id, "sj", this.Sj)
		tx.Exec(sqlstr, xm_id, myddc_id, "gh", this.Gh)
	*/
	err = tx.Commit() //提交事务
	if err != nil {
		log.Println("插入满意度调查表，提交事务出错！", err)
		return err
	}
	return err
}
